package org.zeuzgroup.swing;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;

public class HotKey {

public static void main(String[] args) {
// JLabel to use as a a status bar
final JLabel status = new JLabel(" ", JLabel.TRAILING);

// Create the main window
JFrame frame = new JFrame("Hot Key Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 350);

//
// Define several actions for later use
//
Action fooAction = new AbstractAction("Click me") {
public void actionPerformed(ActionEvent e) {
status.setText("Button in foo tab clicked");
}
};
fooAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

Action barAction = new AbstractAction("Click me") {
public void actionPerformed(ActionEvent e) {
status.setText("Button in bar tab clicked");
}
};
barAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

final Action globalAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
status.setText("Global action key hit");
}
};
globalAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_G, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

//
// Add a listener for the global action
//

// Add listener to AWT toolkit
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
if( event.getID() == KeyEvent.KEY_PRESSED) {
KeyEvent keyEvent = (KeyEvent) event;
if( keyEvent.getKeyCode() == KeyEvent.VK_G &&
keyEvent.getModifiers() == Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) {
globalAction.actionPerformed(null);
keyEvent.consume();
}
}

}
}, AWTEvent.KEY_EVENT_MASK); // We only want key events

//
// Layout the window
//

JPanel fooPanel = new JPanel(new BorderLayout());
JPanel barPanel = new JPanel(new BorderLayout());

fooPanel.add(new JButton(fooAction));
barPanel.add(new JButton(barAction));

JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add(fooPanel, "Foo");
tabbedPane.add(barPanel, "Bar");

frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(status, BorderLayout.SOUTH);

frame.setVisible(true);

}

}